<template>
  <CloudDialog
    v-model:visible="visible"
    title="获取 IP"
    :width="480"
    :mask-closable="false"
    :cancel="handleClose"
    hide-cancel>
    <a-table :data="data" :columns="tableColumn" :pagination="false">
      <template #node_ip="{ record }">
        {{ record.ip }}
      </template>
      <template #action="{ record }">
        <a-link v-if="record.used" :hoverable="false" :disabled="record.used">
          已使用
        </a-link>
        <a-link
          v-else
          :hoverable="false"
          :disabled="useDisabled"
          @click="useIp(record.ip)">
          使用
        </a-link>
      </template>
    </a-table>
    <template #footer>
      <a-button @click="handleClose">关闭</a-button>
    </template>
  </CloudDialog>
</template>
<script lang="ts" setup>
interface IProps {
  reportIps: Array<string>
}

const visible = defineModel<boolean>({ required: true })
const nodeIps = defineModel<Array<{ ip: string }>>('ips', { required: true })
const props = withDefaults(defineProps<IProps>(), {
  reportIps: () => []
})
const data = ref<Array<{ ip: string; used: boolean }>>([])
const tableColumn = buildColumns([
  {
    title: '节点IP',
    slotName: 'node_ip'
  },
  {
    title: '操作',
    slotName: 'action',
    cellClass: 'actions-cell',
    width: 120
  }
])
const useDisabled = computed(() => {
  const index = nodeIps.value.findIndex((item) => item.ip.length === 0)
  if (nodeIps.value.length > 9 && index === -1) {
    return true
  }
  return false
})
const useIp = (ip: string) => {
  const index = nodeIps.value.findIndex((item) => item.ip.length === 0)
  if (index !== -1) {
    nodeIps.value[index] = { ip }
  }
  // nodeIps.value.push({ ip })
}

const handleClose = () => {
  visible.value = false
}
watch(
  () => nodeIps.value,
  (v) => {
    if (v) {
      data.value = props.reportIps?.map((ip) => {
        const index = nodeIps.value.findIndex((item) => item.ip === ip)
        const used = index !== -1 ? true : false

        return { ip, used }
      })
    }
  },
  { immediate: true, deep: true }
)
</script>
